<?php
/**
 * @param string $url
 * @return resource gd imagecreatetruecolor()
 */
function web_page_grabber($url){
  $browser = null;
  $dst_im = null;

  try{
    $browser = new COM('InternetExplorer.Application');
  } catch (Exception $e){
    var_dump($e);
    exit;
  }

  $browser->AddressBar = false;
  $browser->FullScreen = true;
  $browser->MenuBar = false;
  $browser->Silent = true;
  $browser->StatusBar = false;
  $browser->ToolBar = false;
  $browser->Visible = true;

  $browser->Navigate($url);

  while ($browser->Busy) {
    com_message_pump(1000);
  }

  $content_h = $browser->Document->body->clientHeight + $browser->Document->body->offsetTop * 2;
  $content_w = $browser->Document->body->clientWidth + $browser->Document->body->offsetLeft * 2;

  $screen_h = $browser->Document->parentWindow->screen->height;
  $screen_w = $browser->Document->parentWindow->screen->width;

  $SCROLLBAR_WIDTH = 16;

  $last_w = $content_w % $screen_w;
  $last_h = $content_h % $screen_h;

  $offset_x = $screen_w - $SCROLLBAR_WIDTH;
  $offset_y = $screen_h;

  if ($content_h > $screen_h){
    $offset_y = $screen_h - $SCROLLBAR_WIDTH;
  }

  $dst_im = imagecreatetruecolor($content_w, $content_h);

  for ($y=0, $j=0; $y < $content_h; $y+=$offset_y, $j++) {
    for ($x=0, $i=0; $x < $content_w; $x+=$offset_x, $i++) {
      $browser->document->parentWindow->scrollTo($x, $y);
      $src_im = imagegrabwindow($browser->HWND, false);
      $dst_x = $x;
      $dst_y = $y;
      $src_x = 0;
      $src_y = 0;
      $src_w = $screen_w;
      $src_h = $screen_h;

      if ( $x > 0 and ($x+$screen_w) >= $content_w and $last_w > 0) {
        $src_w = $content_w - $x;
        $src_x = $screen_w - $src_w - $SCROLLBAR_WIDTH;
      }
      if ( $y > 0 and ($y+$screen_h) >= $content_h and $last_h > 0) {
        $src_h = $content_h - $y;
        $src_y = $screen_h - $src_h;
        if ($content_w > $screen_w){
          $src_y = $src_y - $SCROLLBAR_WIDTH;
        }
      }
      imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
    }
  }
  $browser->Quit();
  imagedestroy($src_im);
  return $dst_im;
}


/*
Example:

  $url = 'http://www.php.net/downloads.php';
  $filename = date('YmdHis') . '.jpg';
  $im = web_page_grabber($url);
  imagejpeg($im, $filename);
*/
?>